import 'dart:math';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_edit_callback_widget/common_edit_callback_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_pack_up_keyboard_widget/common_pack_up_keyboard_widget.dart';
import 'package:e_reception_flutter/common_widgets/common_title_edit_with_underline_widget/typeof/common_title_edit_with_underline_typeof.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/pages/check_dialog_value_bean.dart';
import 'package:e_reception_flutter/ui/person_detail/bean/person_detail_response_bean.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_tool_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:vg_base/vg_arch_lib.dart';

import '../check_in_statistics_view_model.dart';

class CheckButtonSelectClassWidget extends StatefulWidget {
  // final List<MClassListBean> MClassList;
  final String classIds;

  ///是否从编辑用户进入 （无论是否选择都可以确定）
  final bool fromEditUser;

  const CheckButtonSelectClassWidget(
      {Key key, this.fromEditUser,  this.classIds})
      : super(key: key);

  @override
  _CheckButtonSelectClassWidgetState createState() =>
      _CheckButtonSelectClassWidgetState();

  ///跳转方法
  static Future<EditTextAndValue> navigatorPush(BuildContext context,
     String classIds) {
    return RouterUtils.routeForFutureResult<EditTextAndValue>(
      context,
      CheckButtonSelectClassWidget(classIds: classIds,),
    );
  }
}

class _CheckButtonSelectClassWidgetState
    extends BaseState<CheckButtonSelectClassWidget> {
  // bool isLightUp = false; //确认按钮是否亮起
  List<MClassListBean> selectListCourseItemBean = new List();
  // List<MClassListBean> classIdsSort;
  CheckInStatisicsViewModel _viewModel;
  List<MClassListBean> seartchClassList;
  @override
  void initState() {
    super.initState();
    seartchClassList = List<MClassListBean>();
    _viewModel = CheckInStatisicsViewModel(this);
    // classIdsSort = List<MClassListBean>();

    _viewModel?.classvalueNotifier?.addListener(() {
      // if(_viewModel?.classvalueNotifier?.value?.length != 0){
        seartchClassList = _viewModel?.classvalueNotifier?.value;
      // }
      // else{
      //   seartchClassList = widget?.MClassList;
      // }

      if(selectListCourseItemBean?.length!=0){
        String searchClassIds = selectListCourseItemBean?.map((e) => e?.classid)?.toString();
        seartchClassList?.forEach((element) {
          if(searchClassIds?.contains(element?.classid)){
            element?.isSelect = true;
            // deprtmentids?.add(element);
          }
        });
      }
      if(widget?.classIds!=null && widget?.classIds!=""){
        seartchClassList?.forEach((element) {
          // ignore: null_aware_in_condition
          if(widget?.classIds?.contains(element?.classid?.toString())){
            element?.isSelect = true;
            // classIdsSort?.insert(0, element);
            if(!(selectListCourseItemBean?.map((e) => e?.classid)?.toString()?.contains(element?.classid))){
              selectListCourseItemBean?.add(element);
            }
          }
          // else{
          //   classIdsSort?.add(element);
          // }
        });
        _top();
      }
      setState(() { });
    });

    _viewModel?.getData("01");

    setState(() { });
  }

  void _top(){
    List<MClassListBean> classList = List<MClassListBean>();
    seartchClassList?.forEach((element) {
      if(widget?.classIds?.contains(element?.classid?.toString())){
        element?.isSelect = true;
        classList?.insert(0, element);
      }else{
        classList?.add(element);
      }
    });
    seartchClassList = classList;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      body: CommonPackUpKeyboardWidget(
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            // color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
            _toTopBarWidget(),
            Padding(
              padding: const EdgeInsets.only(left: 7, right: 7, top: 10),
              child: _searchClassWidget(),
            ),
            SizedBox(
              height: 10,
            ),
            //班级list
            _courseClassListWidget(),
            // Spacer(),
            _toHorizontalBar(),
          ],
        ),
      ),
    );
  }

  Widget _toTopBarWidget() {
    return VgTopBarWidget(
      title: "选择班级",
      // rightWidget: ,
    );
  }

  Widget _searchClassWidget() {
    return Container(
      height: 30,
      color: ThemeRepository.getInstance().getBgOrSplitColor_191E31(),
      child: CommonEditCallbackWidget(
        contentPadding: EdgeInsets.only(top: 0, bottom: 15),
        hintText: "搜索",
        customIcon: "images/common_search_ico.png",
        iconColor: Colors.white54,
        onChanged: (String classText) {
          _viewModel?.getData("01",keyword: classText);
        },
      ),
    );
  }

  Widget _toHorizontalBar() {
    return Container(
      height: 56,
      color: Color(0xFF3A3F50),
      // margin: const EdgeInsets.symmetric(horizontal: 15),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: <Widget>[
          SizedBox(
            width: 15,
          ),
          GestureDetector(
              onTap: (){
                if(seartchClassList==null){
                  return;
                }
                if(seartchClassList?.length != selectListCourseItemBean?.length){
                  seartchClassList?.forEach((element) {
                    if(!(element?.isSelect ?? false)){
                      element?.isSelect = true;
                      selectListCourseItemBean.add(element);
                    }
                  });
                }else{
                  seartchClassList?.forEach((element) {
                    element?.isSelect = false;
                    selectListCourseItemBean.remove(element);
                  });
                }
                setState(() { });
              },
              child: Text(((selectListCourseItemBean?.length??0) ==(seartchClassList?.length??0) && (selectListCourseItemBean?.length??0)!=0)?"全不选" :"全选",
                  style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 15))),
          SizedBox(
            width: 15,
          ),
          Text(((selectListCourseItemBean?.length??0) != 0)?"已选${selectListCourseItemBean?.length ?? 0}班级":"",
              style: TextStyle(color: Color(0xFF1890FF), fontSize: 12)),
          Spacer(),
          _buttonWidget(),
          SizedBox(
            width: 15,
          ),
        ],
      ),
    );
  }

  Widget _buttonWidget() {
    return Container(
      child: CommonFixedHeightConfirmButtonWidget(
        isAlive: true,
        width: 90,
        height: 36,
        unSelectBgColor:
            ThemeRepository.getInstance().getTextEditHintColor_3A3F50(),
        selectedBgColor: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
        unSelectTextStyle: TextStyle(
            color: ((selectListCourseItemBean?.length??0) != 0)?VgColors.INPUT_BG_COLOR :VgColors.INPUT_BG_COLOR.withOpacity(0.5),
            fontSize: 15,
            fontWeight: FontWeight.w600),
        selectedTextStyle: TextStyle(
            color:((selectListCourseItemBean?.length??0) != 0) ?ThemeRepository.getInstance().getTextMainColor_D0E0F7() : ThemeRepository.getInstance().getTextMainColor_D0E0F7().withOpacity(0.5), fontSize: 15, fontWeight: FontWeight.w600),
        text: "确定",
        onTap: () {
          //提交按钮
          // if (isLightUp) {
            popResult();
          // }
        },
      ),
    );
  }

  Widget _defaultEmptyCustomWidget() {
    return Expanded(
      child: Padding(
        padding: const EdgeInsets.only(top: 110),
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: <Widget>[
            Image.asset("images/empty_icon.png",width: 120,gaplessPlayback: true,),
            Text(
              "暂无内容",
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                color: VgColors.INPUT_BG_COLOR,
                fontSize: 13,
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _courseClassListWidget() {
    // if((seartchClassList?.length ?? 0)==0){
    //   return _defaultEmptyCustomWidget();
    // }
    return Expanded(
      child: VgPlaceHolderStatusWidget(
        loadingStatus: (seartchClassList?.length??0) == 0 ,
        emptyCustomWidget:_defaultEmptyCustomWidget(),
        child: ListView.separated(
            itemCount: seartchClassList?.length ?? 0,
            padding: const EdgeInsets.all(0),
            physics: BouncingScrollPhysics(),
            keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
            itemBuilder: (BuildContext context, int index) {
              return _toListItemWidget(seartchClassList?.elementAt(index));
            },
            separatorBuilder: (BuildContext context, int index) {
              return Container(
                height: 0.5,
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                padding: const EdgeInsets.only(left: 15),
                child: Container(
                  color: Color(0xFF303546),
                ),
              );
            }),
      ),
    );
  }


  Widget _toListItemWidget(MClassListBean itemBean) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: () {
        itemBean.isSelect = !(itemBean.isSelect ?? false);
        if (itemBean.isSelect) {
          selectListCourseItemBean.add(itemBean);
        } else {
          MClassListBean mbean = MClassListBean();
          selectListCourseItemBean?.forEach((element) {
            if(element?.classid== itemBean?.classid){
              mbean = element;
            }
          });
          selectListCourseItemBean.remove(mbean);
        }
        VgToolUtils.removeAllFocus(context);
        setState(() {});
      },
      child: Container(
        height: 50,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 10,
            ),
            Image(
              image: itemBean.isSelect ?? false
                  ? AssetImage("images/common_selected_ico.png")
                  : AssetImage("images/common_unselect_ico.png"),
              width: 20,
            ),
            SizedBox(
              width: 10,
            ),
            Container(
              width: (VgToolUtils.getScreenWidth()/3)*2,
              child: Text(
                itemBean?.classname ?? "",
                style: TextStyle(color: Color(0xFFD0E0F7), fontSize: 14),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
          ],
        ),
      ),
    );
  }

  ///返回选择结果
  void popResult() {
    String classText = "";
    List<String> classTextList = new List();
    List<String> classTextName = new List();
    if (selectListCourseItemBean?.length != 0 &&
        selectListCourseItemBean != null) {
      selectListCourseItemBean?.forEach((element) {
        classTextList?.add(element?.classid);
        classTextName?.add(element?.classname);
      });
      classText = VgStringUtils?.getSplitStr(classTextList, symbol: ",");
      RouterUtils.pop(context,
          result: EditTextAndValue(value: classText, editText: VgStringUtils?.getSplitStr(classTextName, symbol: ",")));
    }
  }
}
